<template>
	<div class="dynamic-qrcode-view" :style="{ height: options.bg_height + 'px' }">
		<img
			v-if="hasBg"
			ref="bgImg"
			@load="handleBg"
			:src="options.bg_img"
			style="width: 100%;"
			alt="qrcode bg img"
		/>

		<vue-drag-resize
			v-if="options.size"
			parent-limitation
			aspect-ratio
			:parent-h="options.bg_height"
			contentClass="qrcode-box"
			:z-index="100"
			:minw="20"
			:minh="20"
			:sticks="['tl', 'tr', 'br', 'bl']"
			:w="options.size"
			:h="options.size"
			:x="options.left"
			:y="options.top"
			@resizing="onDragResize"
			@dragging="onDragResize"
		>
			<img :src="qrcodeImg" alt="qrcode" style="width: 100%;height: 100%" />
		</vue-drag-resize>
	</div>
</template>
<script>
import VueDragResize from "vue-drag-resize";
import qrcodeImg from "@/cool/modules/ad/assets/qrcode.jpg";
export default {
	name: "dynamic-qrcode-view",
	components: {
		VueDragResize
	},
	props: {
		view: {
			type: Object,
			default: () => ({})
		}
	},
	data() {
		return {
			qrcodeImg,
			options: this.view.options,
			rect: {
				size: 125,
				top: 125,
				left: 125,
				parentH: 375
			},
			initStatus: false
		};
	},
	computed: {
		hasBg() {
			return !!this.options.bg_img;
		}
	},
	watch: {
		hasBg(v) {
			// console.log(1);
			!v && this.handleBg();
		}
	},
	mounted() {
		setTimeout(() => {
			this.$nextTick(() => {
				this.initStatus = true;
				// this.handleBg(this.options);
			});
		}, 1000);
	},
	methods: {
		init() {
			// this.initStatus = true;
			this.$nextTick(() => {
				this.handleBg(this.options);
			});
		},
		onDragResize(rect) {
			console.log("onDragResize", rect);
			if (!this.initStatus) return;
			this.options.size = rect.width;
			this.options.top = rect.top;
			this.options.left = rect.left;
		},
		handleBg(opt = {}) {
			if (!this.initStatus) return;
			this.$nextTick(() => {
				let bgH = this.$refs?.bgImg?.height || 375;
				this.options.bg_height = bgH;
				let size = opt.size ?? 125;
				let left = opt.left ?? 125;
				let top = opt.top ?? ((bgH > 650 ? 650 : bgH) - size) / 2;
				// console.log("top", top);
				this.options.size = size;
				this.$nextTick(() => {
					console.table({ ...this.options });
					this.options.top = top;
					this.options.left = left;
				});
			});
		}
	}
};
</script>
<style lang="scss" scoped>
.dynamic-qrcode-view {
	.qrcode-box.active:before {
		outline-color: $primary;
	}
}
</style>
